package com.xq.sqlSession;

import com.xq.pojo.Configuration;
import com.xq.pojo.MappedStatement;

import java.beans.IntrospectionException;
import java.lang.reflect.*;
import java.sql.SQLException;
import java.util.List;

/**
 * @Author: xiaoqiang
 * @Description:
 * @Date: 2021/5/29
 * @Version: 1.0
 */
public class DefaultSqlSession implements SqlSession {

    private Configuration configuration;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    /**
     * 查询所有
     *
     * @param statementid
     * @param param       查询参数
     * @return
     */
    @Override
    public <E> List<E> selectList(String statementid, Object... param) throws IllegalAccessException, ClassNotFoundException, IntrospectionException, InstantiationException, SQLException, InvocationTargetException, NoSuchFieldException {
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        MappedStatement mappedStatement = configuration.getSql().get(statementid);
        List<Object> query = simpleExecutor.query(configuration, mappedStatement, param);
        return (List<E>) query;
    }

    /**
     * 查询单个信息
     *
     * @param statementid
     * @param param
     * @return
     */
    @Override
    public <E> E selectOne(String statementid, Object... param) throws IllegalAccessException, IntrospectionException, InstantiationException, NoSuchFieldException, SQLException, InvocationTargetException, ClassNotFoundException {
        List<Object> objects = selectList(statementid, param);
        if (objects.size() == 1) {
            return (E) objects.get(0);
        } else {
            throw new RuntimeException("查询结果为空或者结果集大于1");
        }

    }

    /**
     * 为Dao接口生成代理实现类
     *
     * @param mapperClass
     * @return
     */
    @Override
    public <T> T getMapper(Class<?> mapperClass) {

        //使用jdk代理生成代理对象，并返回
        Object o = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //将selectList selectOne，sqlSession中的方法在这里调用，那么需要获取参数 statementid，param
                // 那么怎么获取 statementid 呢，想到了要通过接口（IUDao）可以找到userMapper.xml
                //也就是说要让接口和mapper之间要一一绑定。那么就可以将mapper.xml的namespace设置为IUDao的全路径即可

                String name = method.getName(); //获取到哪个方法调用他了，测试时用的是findAll ，所以name就是findAll
                String className = method.getDeclaringClass().getName(); //获取到接口的名子，也就是IUDao
                String statementid = className + "." + name;

                Type genericReturnType = method.getGenericReturnType(); //获取到findAll 方法的返回值

                //判断返回值类型是否加入了泛型，如果加入了泛型就认为是集合
                if (genericReturnType instanceof ParameterizedType) { //调用selectList
                    List<Object> objects = selectList(statementid, args);
                    return objects;
                }

                return selectOne(statementid, args);
            }
        });

        return (T) o;
    }
}
